<?php
/**
 * @author GhostWei
 * @date Oct 14, 2012
 */
class system_user_controller_advertise extends system_user_controller_panel {	

	protected $concept = null;
	public function init() {
		if(!parent::init()) {
			return ;
		}
		$this->concept = new resource_advertise_concept();
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Resource'))->setRoute('resource/index'));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Advertisements'))->setRoute('resource/advertise/index'));
	}
	
	protected function _itemAddnew($row) {
		$time = system_date::timestamp();
		$concept = new resource_advertise_item_concept();
		$item = $concept->create();
		$item->setDisplayOrder(0);
		$item->setIsLayout(0);
		$this->view->langs = $this->_defaultLangs();
		$this->view->devices = array();
		$item = $this->_itemSaveRow($item, $row);
		$this->view->referer = $this->referer;		
		$this->view->item = $item;
		$this->render('resource/advertise/itemRow.phtml');
	}
	
	protected function _itemEdit($row) {
		$id = intval($this->_param('item_id'));
		$concept = new resource_advertise_item_concept();
		if(!($item = $concept->fetch(array('item.id = ?' => $id)))) {
			throw new resource_exception('this advertisement item is not existing.');
		}
		$concept = new resource_advertise_lang_concept();
		$langs = array();
		foreach($concept->fetchAll(array('item_id = ?' => $item->getId())) AS $lang) {
			$langs[strtolower($lang->getLang())] = array(
					'checked' => true,
					'start_time' => $lang->getStartTime(),
					'end_time' => $lang->getEndTime()
			);
		}
		$this->view->langs = array_merge($this->_defaultLangs(false), $langs);
		$concept = new resource_advertise_device_concept();
		$devices = array();
		foreach($concept->fetchAll(array('item_id = ?' => $item->getId())) AS $device) {
			$devices[] = strtolower($device->getDeviceKey());
		}
		$this->view->devices = $devices;
		$item = $this->_itemSaveRow($item, $row);
		$this->view->referer = $this->referer;
		$this->view->item = $item;
		$this->render('resource/advertise/itemRow.phtml');
	}
	
	protected function _defaultLangs($setDefault = true) {
		$langs = array();
		$time = system_date::timestamp();
		foreach(new system_setting_language() AS $lang) {
			$langs[strtolower($lang->getKey())] = array(
					'checked' => $this->user->getLang() == strtolower($lang->getKey()) && $setDefault ? true :false,
					'start_time' => strtotime(date('Y-m-d 0:0:0', $time)),
					'end_time' => strtotime(date('Y-m-d 23:59:59', $time + 86400))
			);
		}
		return $langs;
	}
	
	protected function _itemSaveRow($row, $ad) {
		if(!$this->getRequest()->isPost()) {
			return $row;
		}
		$this->referer = $this->_post('referer');
		$langs = array();
		foreach((array) $this->_post('lang') AS $key => $lang) {
			$langs[$key] = array(
					'checked' => isset($lang['checked']) ? true : false,
					'start_time' => $this->_constructTime($lang['start_time']),
					'end_time' => $this->_constructTime($lang['end_time']),
			);
			if(isset($lang['checked'])) {
				$row->addLangList($key, $langs[$key]);
			}
		}
		$this->view->devices = $devices = (array) $this->_post('device');
		$this->view->langs = $langs;
		foreach($devices AS $device) {
			$row->addDeviceList($device);
		}
		$row->setAdvertiseId($ad->getId());
		$row->setDisplayOrder(intval($this->_post('display_order')));
		$row->setIsLayout(intval($this->_post('is_layout')));
		$row->setDescription(trim($this->_post('description')));
		$row->setUrl(trim($this->_post('url')));
		$row->setScript($this->_post('script'));
		$row->setScriptBody($this->_post('script_body'));
		$row->setStyle($this->_post('style'));
		$row->setStyleBody($this->_post('style_body'));
		$this->_saveToDatabase($row, 'hash', 'advertise', false);	
		if(!$this->view->throwException) {
			$this->view->advertise($ad->getName())->remove();
		}			
		return $row;
	}
	
	protected function _constructTime(array $time) {
		$_time = null;
		if(isset($time['date']) && $time['date']) {
			$_time = $time['date'] . ' ';
			unset($time['date']);
			$_time .= implode(':', $time);
			$_time = strtotime($_time);
		}
		return $_time;
	}
	
	protected function _itemList($row) {
		$concept = new resource_advertise_item_concept();
		$this->_batchDelete($concept, 'id', 'item.id');
		$adapter = new system_paginator_adapter_concept($concept);
		$adapter->where('item.advertise_id = ?', $row->getId());
		$adapter->setCurrentPageNumber(intval($this->_param('page', 1)));
		$adapter->setLimit(30);
		$this->view->order = $order = strtolower($this->_get('order'));
		$_order = array("item.id DESC");
		if($order) {
			$this->view->sort = $sort = intval($this->_get('sort'));
			$_sort = !$sort ? 'DESC' : 'ASC';
			if($order == 'id') $order = 'item.id';
			if($order == 'display_order') $order = 'item.display_order';
			$_order = array("$order $_sort");
		}
		$adapter->order($_order);
		$list = new system_paginator($adapter);
			
		$ids = $langs = $devices = array();
		foreach($list AS $row) {
			$ids[] = $row->getId();
		}
		if(!empty($ids)) {
			$_ids = implode(', ', $ids);
			$sql = "SELECT item_id, lang, start_time, end_time FROM resource_advertise_lang WHERE item_id IN($_ids)";
			foreach(system_db::getAdapter()->fetchAll($sql) AS $_row) {
				$langs[$_row['item_id']][$_row['lang']] = $_row;
			}
			$sql = "SELECT item_id, device_key FROM resource_advertise_device WHERE item_id IN($_ids)";
			foreach(system_db::getAdapter()->fetchAll($sql) AS $_row) {
				$devices[$_row['item_id']][] = $_row['device_key'];
			}
		}
		//print_r($langs);exit;
		$this->view->devices = $devices;
		$this->view->langs = $langs;
		$this->view->list = $list;
		$this->render();
	}
	
	protected function _getRow() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('advertise.id = ?' => $id)))) {
			throw new resource_exception('this advertisement is not existing.');
		}
		return $row;
	}
	
	protected function _saveRow($row) {
		if(!$this->getRequest()->isPost()) {
			return $row;
		}
		$this->referer = $this->_post('referer');
		$row->setName(trim($this->_post('name')));
		$row->setDescription(trim($this->_post('description')));
		$row->setUrl(trim($this->_post('url')));
		$row->setWidth(intval($this->_post('width')));
		$row->setHeight(intval($this->_post('height')));	
		$this->_saveToDatabase($row, 'hash', 'advertise', false);	
		if(!$this->view->throwException) {
			$this->view->advertise($row->getName())->remove();
		}		
		return $row;
	}

}
